<template>
  <div id="app">
    <!-- 用户表 -->
    <el-card shadow="always" class="table-card">
      <div slot="header" class="clearfix">
        <span>用户表</span>
      </div>
      <el-table
          :data="userList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            label="用户号"
            align="center"
            prop="uid"/>
        <el-table-column
            label="用户名"
            prop="uname"
            align="center"/>
        <el-table-column
            label="姓名"
            prop="name"
            align="center"/>
        <el-table-column
            label="性别"
            prop="sex"
            align="center"/>
      </el-table>
      <!-- 分页导航面板 -->
      <el-pagination
          @size-change="handleUserSizeChange"
          @current-change="handleUserCurrentChange"
          :current-page="userPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="userPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="userTotal">
      </el-pagination>
    </el-card>

    <!-- 书籍表 -->
    <el-card shadow="always" class="table-card">
      <div slot="header" class="clearfix">
        <span>馆藏书籍</span>
      </div>
      <el-form :inline="true" size="medium" :model="bookSearch" class="demo-form-inline">
        <!--条件查询-->
        <el-form-item>
          <el-input v-model="bookSearch.bname" placeholder="书名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="bookSearch.writer" placeholder="作者"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="searchBooks">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addBook">添加书籍</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="bookList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            label="书籍编号"
            align="center"
            prop="bid"/>
        <el-table-column
            label="书名"
            prop="bname"
            align="center"/>
        <el-table-column
            label="作者"
            prop="writer"
            align="center"/>
        <el-table-column
            label="类型"
            prop="btype"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页导航面板 -->
      <el-pagination
          @size-change="handleBookSizeChange"
          @current-change="handleBookCurrentChange"
          :current-page="bookPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="bookPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="bookTotal">
      </el-pagination>
    </el-card>

    <!-- 借阅记录表 -->
    <el-card shadow="always" class="table-card">
      <div slot="header" class="clearfix">
        <span>借阅记录</span>
      </div>
      <el-table
          :data="recordList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            label="序号"
            align="center"
            prop="brid"/>
        <el-table-column
            label="用户名"
            prop="uname"
            align="center"/>
        <el-table-column
            label="姓名"
            prop="name"
            align="center"/>
        <el-table-column
            label="借阅图书"
            prop="bname"
            align="center"/>
        <el-table-column
            label="借阅时间"
            prop="brdate"
            align="center"/>
      </el-table>
      <!-- 分页导航面板 -->
      <el-pagination
          @size-change="handleRecordSizeChange"
          @current-change="handleRecordCurrentChange"
          :current-page="recordPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="recordPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="recordTotal">
      </el-pagination>
    </el-card>

    <!-- 编辑【添加/修改】书籍对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
<!--      {{book }}-->
      <el-form :model="book" :rules="rules" ref="ruleForm">
        <el-form-item label="书籍名" prop="bname" :label-width="formLabelWidth">
          <el-input v-model="book.bname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者姓名" prop="writer" :label-width="formLabelWidth">
          <el-input v-model.number="book.writer" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍类型" prop="btype" :label-width="formLabelWidth">
          <el-input v-model.number="book.btype" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveBook">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import bookApi from "@/api/books"
import userApi from "@/api/users"
import recordApi from "@/api/records"


export default {
  data() {
    return {
      userList: [],//所有用户
      userPage: 1,
      userPageSize: 5,
      userTotal: 100,
      bookList: [],   // 所有书籍
      bookPage: 1,
      bookPageSize: 5,
      bookTotal: 100,
      recordList:[], //所有借阅记录
      recordPage: 1,
      recordPageSize: 5,
      recordTotal: 100,
      recordSearch: {}, // 条件查询对象
      bookSearch: {},//书籍查询对象
      dialogFormVisible: false,  // 代表对话框的显示状态
      book:{},//代表添加或修改的书籍
      title:"添加书籍",//对话框标题
      formLabelWidth:"120px",//表单的标签宽度
      multipleSelection:[],//选中项
      bids:[],//删除的记录编号
      rules: {
        bname: [
          {required: true, message: '请输入书籍名', trigger: 'blur'},
        ],
        writer: [
          {required: true, message: '请输入作者', trigger: 'blur'},
        ],
        btype: [
          {required: true, message: '请输入类型', trigger: 'blur'},
        ],
      }
    }
  },
  created() {
     // this.findAllUsers()
     // this.findAllBooks()
      //this.findAllRecords()
    //this.searchRecord()
    this.findUsersByPage()
    //this.findBooksByPage()
    this.searchBooks()
    this.searchRecords()
    //this.findRecordsByPage()
  },
  methods: {
    async findAllUsers() {//所有用户
      try {
        const { data: res } = await userApi.findAllUsers()
        console.log(res)
        if (res.code === 200) {
          this.userList = res.data.list
        }
      } catch (error) {
        console.error("查询所有用户失败:", error)
      }
    },
    async findAllBooks() {//所有用户
      try {
        const { data: res } = await bookApi.findAllBooks()
        console.log(res)
        if (res.code === 200) {
          this.bookList = res.data.list
        }
      } catch (error) {
        console.error("查询所有书籍失败:", error)
      }
    },
    async findAllRecords() {//所有记录
      try {
        const { data: res } = await recordApi.findAllRecords()
        console.log(res)
        if (res.code === 200) {
          this.recordList = res.data.list
        }
      } catch (error) {
        console.error("查询所有借阅记录失败:", error)
      }
    },
    async findUsersByPage() {//分页功能
      const {data:res} = await userApi.findUsersByPage(this.userPage,this.userPageSize)
      console.log(res)
      if (res.code === 200) {
        this.userList = res.data.list.rows
        this.userTotal = res.data.list.total
      }
    },
    async findBooksByPage() {//分页功能
      const {data:res} = await bookApi.findBooksByPage(this.bookPage,this.bookPageSize)
      console.log(res)
      if (res.code === 200) {
        this.bookList = res.data.list.rows
        this.bookTotal = res.data.list.total
      }
    },
    async findRecordsByPage() {//分页功能
      const {data:res} = await recordApi.findRecordsByPage(this.recordPage,this.recordPageSize)
      console.log(res)
      if (res.code === 200) {
        this.recordList = res.data.list.rows
        this.recordTotal = res.data.list.total
      }
    },
    async searchBooks() {//查询书籍并实现分页功能
      try {
        const { data: res } = await bookApi.searchBook(this.bookPage, this.bookPageSize, this.bookSearch)
        console.log(res)
        if (res.code === 200) {
          this.bookList = res.data.list.rows
          this.bookTotal = res.data.list.total
        }
      } catch (error) {
        console.error("条件查询书籍失败:", error)
      }
    },
    async searchRecords() {//查询借阅记录并实现分页功能
      try {
        const { data: res } = await recordApi.search(this.recordPage, this.recordPageSize, this.recordSearch)
        console.log(res)
        if (res.code === 200) {
          this.recordList = res.data.list.rows
          this.recordTotal = res.data.list.total
        }
      } catch (error) {
        console.error("条件查询记录失败:", error)
      }
    },
    addBook() {//添加书籍
      this.title="添加书籍"
      this.book={}
      this.dialogFormVisible = true
    },
    saveBook() {//保存书籍
      this.$refs.ruleForm.validate(async valid=> {
        //根据是否有sid来决定添加还是修改，没有sid就是添加，有就是修改
        let url = "/book/add"      // 默认地址是添加学生
        let method = "post"           // 添加是post请求
        if(this.book.bid){
          url = "/book/update"    // 如果有值就改为修改学生
          method = "put"             // 修改是put请求
        }
        //执行添加或修改
        if (valid) {
          const {data:res} = await bookApi.saveBook(url,method,this.book)
          console.log("res:",res)
          if (res.code === 200) {     // 后端执行成功返回200
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {        // 关闭对话框时的回调
                // 6.3 关闭对话框
                this.dialogFormVisible = false
                // 6.4 重新查询
                this.searchBooks()
              }
            })
          }else{                      // 后端执行失败返回500
            this.$message({
              type: 'error',
              message: res.message,
            })
          }
        }else{
          console.log("验证失败")
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    // 用户表分页处理方法
    handleUserSizeChange(val) {
      this.userPageSize = val;
      this.findUsersByPage();
      console.log(`每页 ${val} 条`);
    },
    handleUserCurrentChange(val) {
      this.userPage = val;
      this.findUsersByPage();
      console.log(`当前页: ${val}`);
    },

    // 书籍表分页处理方法
    handleBookSizeChange(val) {
      this.bookPageSize = val;
      //this.findBooksByPage();
      this.searchBooks();
      console.log(`每页 ${val} 条`);
    },
    handleBookCurrentChange(val) {
      this.bookPage = val;
      //this.findBooksByPage();
      this.searchBooks();
      console.log(`当前页: ${val}`);
    },

    // 借阅记录表分页处理方法
    handleRecordSizeChange(val) {
      this.recordPageSize = val;
      //this.findRecordsByPage();
      this.searchRecords();
      console.log(`每页 ${val} 条`);
    },
    handleRecordCurrentChange(val) {
      this.recordPage = val;
      //this.findRecordsByPage();
      this.searchRecords();
      console.log(`当前页: ${val}`);
    },
    handleEdit(index, row) {//编辑书籍
      //打开对话框
      this.title = "修改书籍信息"
      //显示数据
      this.book = row
      this.dialogFormVisible = true
      console.log(index, row);
    },
    handleDelete(index, row) {//删除book，单个或者批量的
      this.bids=[]
      if(row){
        this.bids.push(row.bid);
      }else {
        this.bids=this.multipleSelection.map(m=>m.bid)
      }
      this.$confirm(`是否删除书籍编号为${this.bids}的书`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {//点击确定后执行
        let _this = this
        bookApi.delete(this.bids)
            .then(({data:res}) => {
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    // 重新加载数据
                    _this.searchBooks()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {//点击取消
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
      console.log("sids:",this.bids);
      console.log(index, row);
    }
  }
}
</script>

<style scoped>
/* 确保卡片之间有一定的间距 */
.table-card {
  margin-bottom: 20px;
}

.clearfix {
  text-align: center;
}
</style>
